package com.xiaoxu.rental.security;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.xiaoxu.rental.util.Result;
import com.xiaoxu.rental.util.ResultCode;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Title: CustomerAccessDeniedHandler
 * @Author Mr.Xu
 * @Package com.xiaoxu.rental.security
 * @Date 2024/7/25 15:20
 * @description:
 */
@Component
public class CustomerAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       AccessDeniedException accessDeniedException) throws IOException, ServletException {

        response.setContentType("application/json;charset=utf-8");

//        ServletOutputStream outputStream = response.getOutputStream();
//        String result = JSON.toJSONString(Result.fail().setCode(ResultCode.UNAUTHORIZED)
//                .setMessage("无权访问"));
//        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
//        outputStream.flush();
//        outputStream.close();

        // 使用 JSON 格式化错误信息
        String result = JSONUtil.toJsonStr(Result.fail()
                .setCode(ResultCode.UNAUTHORIZED)
                .setMessage("无权访问"));

        // 使用 IoUtil 直接写入输出流
        IoUtil.write(response.getOutputStream(), false, result.getBytes());

    }
}
